#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/08/26 14:00:05
'''
import sys
sys.path.append('.')
import threading
import time
from timing.utils import DbManager

from models.user_models import EntityUser, EntityUserFace
from models.client_models import EntityClientCellUser, EntityClientUser
from db_logic.client_cell_user import BllClientCellUser
from db_logic.user import BllUser
from db_logic.client_user import BllClientUser
from db_logic.user_face import BllUserFace
from Common.Utils import Utils

class TimingBase(object):

    time_sleep = 60
    timing_status = True
    db_list = ["rms_client_cell_user",
               "rms_client_user",
               "rms_user",
               "rms_user_face"
               ]

    def get_db_obj(self, table_name):
        dic = {
            "rms_client_cell_user": BllClientCellUser(),
            "rms_client_user": BllClientUser(),
            "rms_user": BllUser(),
            "rms_user_face": EntityUserFace()
        }
        return dic.get(table_name)
    
    def get_db_table(self, table_name):
        dic = {
            "rms_client_cell_user": EntityClientCellUser(),
            "rms_client_user": EntityClientUser(),
            "rms_user": EntityUser(),
            "rms_user_face": BllUserFace()
        }
        return dic.get(table_name)
    

    def sync_db(self):
        while self.timing_status:
            try:
                db_manager = DbManager()
                for i in self.db_list:
                    local_data = self.get_db_obj(i)
                    if not local_data:
                        continue
                    data_list = local_data.execute(
                        f"select * from {i}").fetchall()
                    if not data_list:
                        continue
                    data_list = Utils.msyql_table_model(data_list)
                    # db_manager.insert_ignore(
                    #     **{"table": i, "data": data_list, "update_obj": local_data})
                    db_manager.insert_ignore_update(
                        **{"table": i, "data": data_list})
            finally:
                db_manager.close()
            time.sleep(self.time_sleep)

    def start(self):
        p = threading.Thread(target=self.sync_db, daemon=True)
        p.start()
    

    def stop(self):
        self.timing_status = False

